package net.zoneland.data.dataprofiling.system.service.impl;

import net.zoneland.data.dataprofiling.system.domain.RoleEntity;
import net.zoneland.data.dataprofiling.system.domain.UserEntity;
import net.zoneland.data.dataprofiling.system.repository.RoleRepository;
import net.zoneland.data.dataprofiling.system.repository.UserRepository;
import net.zoneland.data.dataprofiling.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {


    public static final String ROLE_ALL_KEY = "\"role_all\"";

    public static final String DEMO_CACHE_NAME = "role";

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    public RoleEntity get(Long id) {
        return roleRepository.getOne(id);
    }

    @Override
    public List<RoleEntity> list() {
        return roleRepository.findAll();
    }

    @Transactional
    @Override
    public int save(RoleEntity role) {
        roleRepository.save(role);
        return 1;
    }

    @Override
    public int update(RoleEntity role) {
        roleRepository.saveAndFlush(role);
        return 1;
    }

    @Override
    public int remove(Long id) {
        roleRepository.deleteById(id);
        return 1;
    }

    @Override
    public List<RoleEntity> list(Long userId) {
        UserEntity userEntity = userRepository.getOne(userId);
        List<RoleEntity> roles = list();
        for(RoleEntity roleEntity:roles){
            roleEntity.setRoleSign("false");
            for(RoleEntity roleEntity1:userEntity.getRoles()){
                if(roleEntity.equals(roleEntity1)){
                    roleEntity.setRoleSign("true");
                    break;
                }
            }
        }
        return roles;

    }

    @Override
    public int batchremove(Long[] ids) {
        for(Long id:ids){
            remove(id);
        }
        return ids.length;
    }
}
